<template>
  <ToolbarButton
    type="dropdown"
    icon="i-tabler-grid-pattern"
    title="页面底纹"
    dropdown-icon="i-ri-arrow-down-s-fill"
    popover-width="240px"
    popover-placement="bottom-start"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    @main-click="togglePageBackground"
  >
    <template #dropdown>
      <div class="page-background-dropdown">
        <!-- 底纹选项 -->
        <div class="page-background-options">
          <div
            v-for="option in backgroundOptions"
            :key="option.value"
            class="page-background-option"
            :class="{ active: currentBackground === option.value }"
            @click="setPageBackground(option.value)"
          >
            <!-- 选中标记 -->
            <div class="page-background-check">
              <i
                v-if="currentBackground === option.value"
                class="i-ri-check-line"
              ></i>
            </div>
            <!-- 预览区域 -->
            <div 
              class="page-background-preview" 
              :class="option.value.startsWith('#') ? 'color-preview' : option.value"
              :style="option.value.startsWith('#') ? { '--preview-color': option.value } : {}"
            >
              <div 
                class="preview-content"
                :style="option.value.startsWith('#') ? { background: option.value } : {}"
              ></div>
            </div>
            <!-- 选项信息 -->
            <div class="page-background-info">
              <div class="background-label">{{ option.label }}</div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { inject, computed, type Ref } from "vue";
import type { PageOption } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { closeAllToolbarPopups } from "../../../button/src/utils/toolbarPopupManager";
import { BACKGROUND_OPTIONS } from "../../../../config/constants";

defineOptions({
  name: "PageBackground",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

// 注入页面配置
const pageOptions = inject<Ref<PageOption>>("page");

// 底纹选项
const backgroundOptions = BACKGROUND_OPTIONS;

// 当前选中的底纹
const currentBackground = computed(() => {
  // 根据 pageOptions.value.background 判断当前底纹类型
  const background = pageOptions?.value?.background || "#ffffff";
  
  // 如果背景是纯色，返回对应的颜色值
  if (background.startsWith("#") || background.startsWith("rgb")) {
    // 标准化颜色值进行比较
    const normalizedBg = background.toLowerCase().trim();
    // 检查是否匹配预设颜色
    const colorOption = backgroundOptions.find(opt => opt.value === normalizedBg);
    return colorOption ? colorOption.value : normalizedBg;
  }
  
  // 如果包含 repeating-linear-gradient 或 radial-gradient，说明是底纹图案
  if (background.includes("repeating-linear-gradient")) {
    if (background.includes("0deg") && background.includes("90deg")) {
      // 包含两个方向的渐变，是网格或方格
      if (background.includes("10px")) return "grid";
      if (background.includes("15px")) return "squares";
    } else {
      // 只有一个方向的渐变，是横线
      return "lines";
    }
  }
  
  if (background.includes("radial-gradient")) {
    return "dots";
  }
  
  return "#ffffff";
});

// 切换页面底纹（主按钮点击）
const togglePageBackground = () => {};

// 设置页面底纹
const setPageBackground = (background: string) => {
  if (!pageOptions?.value) return;
  
  let backgroundValue = "#ffffff";
  
  // 如果是颜色值（以 # 开头），直接使用
  if (background.startsWith("#")) {
    backgroundValue = background;
  } else if (background === "grid") {
    // 网格底纹
    backgroundValue = `repeating-linear-gradient(0deg, transparent, transparent 10px, rgba(0,0,0,0.03) 10px, rgba(0,0,0,0.03) 11px),
                  repeating-linear-gradient(90deg, transparent, transparent 10px, rgba(0,0,0,0.03) 10px, rgba(0,0,0,0.03) 11px)`;
  } else if (background === "lines") {
    // 横线底纹
    backgroundValue = `repeating-linear-gradient(0deg, transparent, transparent 20px, rgba(0,0,0,0.05) 20px, rgba(0,0,0,0.05) 21px)`;
  } else if (background === "dots") {
    // 点阵底纹 - 使用两个径向渐变叠加
    backgroundValue = `radial-gradient(circle, rgba(0,0,0,0.1) 1px, transparent 1px),
                  radial-gradient(circle, rgba(0,0,0,0.1) 1px, transparent 1px)`;
  } else if (background === "squares") {
    // 方格底纹
    backgroundValue = `repeating-linear-gradient(0deg, transparent, transparent 15px, rgba(0,0,0,0.05) 15px, rgba(0,0,0,0.05) 16px),
                  repeating-linear-gradient(90deg, transparent, transparent 15px, rgba(0,0,0,0.05) 15px, rgba(0,0,0,0.05) 16px)`;
  }
  
  // 更新页面背景
  pageOptions.value.background = backgroundValue;
  
  // 关闭 dropdown 弹窗
  closeAllToolbarPopups(undefined, undefined, ["select", "popover"]);
};
</script>

<style lang="scss" scoped>
.page-background-dropdown {
  padding: 8px;
}

.page-background-options {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-background-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
  background-color: transparent;

  &:hover {
    background-color: transparent;
  }

  &.active {
    background-color: transparent;
  }
}

.page-background-check {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;

  .i-ri-check-line {
    font-size: 16px;
    color: var(--editor-primary-color, #0D61F2);
    transition: color 0.2s ease;
  }
}

.page-background-preview {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  border: 1px solid var(--editor-border-color);
  border-radius: 4px;
  overflow: hidden;
  background-color: #ffffff;

  .preview-content {
    width: 100%;
    height: 100%;
  }

  &.color-preview {
    .preview-content {
      background: var(--preview-color, #ffffff);
    }
  }

  &.grid {
    .preview-content {
      background: repeating-linear-gradient(
          0deg,
          transparent,
          transparent 5px,
          rgba(0, 0, 0, 0.1) 5px,
          rgba(0, 0, 0, 0.1) 6px
        ),
        repeating-linear-gradient(
          90deg,
          transparent,
          transparent 5px,
          rgba(0, 0, 0, 0.1) 5px,
          rgba(0, 0, 0, 0.1) 6px
        );
    }
  }

  &.lines {
    .preview-content {
      background: repeating-linear-gradient(
        0deg,
        transparent,
        transparent 8px,
        rgba(0, 0, 0, 0.15) 8px,
        rgba(0, 0, 0, 0.15) 9px
      );
    }
  }

  &.dots {
    .preview-content {
      background: radial-gradient(circle, rgba(0, 0, 0, 0.2) 1px, transparent 1px);
      background-size: 8px 8px;
    }
  }

  &.squares {
    .preview-content {
      background: repeating-linear-gradient(
          0deg,
          transparent,
          transparent 6px,
          rgba(0, 0, 0, 0.1) 6px,
          rgba(0, 0, 0, 0.1) 7px
        ),
        repeating-linear-gradient(
          90deg,
          transparent,
          transparent 6px,
          rgba(0, 0, 0, 0.1) 6px,
          rgba(0, 0, 0, 0.1) 7px
        );
    }
  }
}

.page-background-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.background-label {
  font-size: 14px;
  font-weight: 700;
  color: var(--editor-text-color);
  line-height: 1.5;
}

/* 暗色主题适配 */
[theme-mode="dark"] {
  .page-background-preview {
    background-color: var(--editor-color-dark);
    border-color: var(--editor-border-color);

    &.none {
      .preview-content {
        background: var(--editor-color-dark);
      }
    }
  }

  .page-background-option {
    background-color: transparent;

    &:hover {
      background-color: transparent;
    }

    &.active {
      background-color: transparent;
    }
  }
}
</style>

